<?php

/* ----------------------------------------------
  Caloris: Administration Login Page

  $Id$
  $Author$

  Přihlašovací stránka do administrace
  ---------------------------------------------- */

require_once("../../../index.php");

define('_MODULE_ACTIVE', 'administrator');

// Login Form

$formLogin = new Nette\Forms\Form;
$formLogin->setAction(_CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php');
$formLogin->addHidden('function_name', 'login');
$formLogin->addText('val_0', t('username', 'administrator') . ':')
        ->addRule(Nette\Forms\Form::MIN_LENGTH, t('usernameMustBeLonger', 'administrator'), 5)
        ->addRule(Nette\Forms\Form::MAX_LENGTH, t('usernameMustBeShorter', 'administrator'), 40)
        ->setAttribute('autofocus')
        ->setAttribute('autocomplete', 'off');
$formLogin->addPassword('val_1', t('password', 'administrator') . ':')
        ->addRule(Nette\Forms\Form::MIN_LENGTH, 6);
$formLogin->addCheckbox('remember', t('doNotLogOut', 'administrator'))
        ->setDefaultValue("CHECKED");
$formLogin->addSubmit('send', t('login', 'administrator'));

$renderer = $formLogin->getRenderer();
$renderer->wrappers['controls']['container'] = 'dl class="loginForm cform"';
$renderer->wrappers['pair']['container'] = NULL;
$renderer->wrappers['label']['container'] = 'dt';
$renderer->wrappers['control']['container'] = 'dd';

if ($formLogin->isSubmitted() && $formLogin->isValid()) {
    $auser = $_POST["val_0"];
    $apwd = $_POST["val_1"];
    $remember = \Caloris\Tools::checknull($remember);
    $auser = \Caloris\Text::protect($auser); // String protection
    $apwd_enc = \Caloris\ACL::passHash($apwd);

    // Checks existence of the user account
    $xmlUser = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
    $xmlUserEdit = $xmlUser->xpath('//user[@id="' . $auser . '"]');

    if (count($xmlUserEdit) == 0) {
        header('Location: ' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php?msg=' . urlencode('Zadali jste chybné uživatelské jméno'));
    }

    if (strcmp($xmlUserEdit[0]->password, $apwd_enc) != 0) {

        header('Location: ' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php?msg=' . urlencode('Zadali jste chybné heslo'));
        exit();
    }

    // Blocked account
    if ($xmlUserEdit[0]->state->permissions == 0) {
        header('Location: ' . ln('login', '', 'msg=' . urlencode("Váš účet byl zablokován")));
        exit();
    }

    $xmlUserEdit[0]->date->visited = date(_CALSET_BASIC_DATE_FORMAT . " " . _CALSET_BASIC_TIME_FORMAT);
    $xmlUser->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');

    if ($_POST["remember"] == 'on') {
        setcookie("auser", $auser, time() + 60 * 60 * 24 * 15, "/");
        setcookie("apwd", $apwd_enc, time() + 60 * 60 * 24 * 15, "/");
    } else {
        setcookie("auser", $auser, 0, "/");
        setcookie("apwd", $apwd_enc, 0, "/");
    }

    header('Location: ' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/index.php');
    exit();
}

if ($_REQUEST["function_name"] == 'logout') {
    \Caloris\ACL::authenticate();
    setcookie("auser", "", time() - 60 * 60 * 24 * 15, "/");
    setcookie("apwd", "", time() - 60 * 60 * 24 * 15, "/");

    header('Location: ' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php?msg=' . urlencode(t('loggedOut', 'administrator')));
    exit();
}

if ($_POST["action"] == 'passLostRetrieve') {
    $email = $_POST["email"];

    $genpwd = \Nette\Utils\Strings::random(12, "00123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");

    $xmlUser = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
    $xmlUserLostPassword = $xmlUser->xpath('//user[email="' . $email . '"]');

    if (count($xmlUserLostPassword) == 0) {
        header("location:" . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/login.php?action=passLost&msg=" . urlencode("Vámi zadaný e-mail nebyl nalezen."));
        exit();
    }

    $urlAddress = _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php?action=passRetrieve';
    $uri = _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . "/login.php";

    $xmlUserLostPassword[0]->password = $ppwd_enc;
    $xmlUserLostPassword[0]->state->activation = $genpwd;
    $xmlUser->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');

    // Creates message body

    $message = "
Dobrý den,<br />
<br />
Zřejmě jste požádali o zaslání Vašeho hesla. Kliknutím na odkaz dole se dostanete na stránku, kde si můžete zvolit nové heslo.<br />
<br />
<a href=\"" . $urlAddress . "&email=$email&code=$genpwd\">" . $urlAddress . "&email=$email&code=$genpwd</a><br />
<br />
Jestliže máte jakýkoliv problém, dejte nám vědět na " . _CALSET_BASIC_ADMIN_EMAIL . ". Použijte e-mail, kterým jste se registrovali k této stránce.<br />
<br />

" . _CALSET_BASIC_TITLE . " - " . _CALSET_PATHS_URI . "
";

    $headers .= 'Content-type: text/html; charset=utf-8' . "\n";
    $headers .= "From: " . _CALSET_BASIC_TITLE . " <" . _CALSET_BASIC_ADMIN_EMAIL . ">\n";

    // Sending message
    $subject = "=?utf-8?B?" . base64_encode(_CALSET_BASIC_TITLE . ": Informace o novém hesle") . "?=";

    if (@mail($email, $subject, $message, $headers)) {
        header("location:" . $uri . "?msg=" . urlencode("E-mail odeslán"));
        exit();
    } else {
        header("location:" . $uri . "?msg=" . urlencode("Nastala chyba, e-mail nebyl odeslán"));
        exit();
    }
}

if ($_POST["action"] == 'passRetrieveReset') {
    $email = $_POST["email"];
    $activationcode = $_POST["activation"];
    $pwd = $_POST["pwd"];
    $pwd2 = $_POST["pwd2"];

    // Password check
    $xmlUser = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
    $xmlUserResetPassword = $xmlUser->xpath('//user[email="' . $email . '"]');


    $urlAddress = _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php?action=passRetrieve';

    if (count($xmlUserResetPassword) == 0) {
        header("location:" . $urlAddress . "&email=" . $email . "&code=" . $activationcode . "&msg=" . urlencode("Neexistující e-mail"));
        exit();
    }

    if ($xmlUserResetPassword[0]->state->activation == '') {
        header("location:" . $urlAddress . "&email=" . $email . "&code=" . $activationcode . "&msg=" . urlencode("Prošlá aktivace"));
        exit();
    }

    if (Caloris\ACL::passCheck($pwd) == false) {
        header("location:" . $urlAddress . "&email=" . $email . "&code=" . $activationcode . "&msg=" . urlencode("Nesprávné heslo"));
        exit();
    }

    if (strcmp($pwd, $pwd2) <> 0) {
        header("location:" . $urlAddress . "&email=" . $email . "&code=" . $activationcode . "&msg=" . urlencode("Hesla nejsou stejná"));
        exit();
    }

    $ppwd_enc = Caloris\ACL::passHash($pwd);

    $xmlUserResetPassword[0]->password = $ppwd_enc;
    $xmlUserResetPassword[0]->state->activation = $activationcode;
    $xmlUser->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');

    header('Location: ' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . "/login.php?action=passRetrieve&email=" . $email . "&code=" . $activationcode . "&msg=" . urlencode("Heslo bylo změněno. Nyní se můžete přihlásit s vašim novým heslem."));
    exit();
}

$content = '
<!DOCTYPE html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="' . _CALSET_PATHS_URI . _CALSET_DIRS_TEMPLATE . '/caloris-admin/css/style.css" type="text/css" media="screen,projection" />
    <title>' . t('loggingIn', 'administrator') . '</title>
</head>
<body>
<div class="container">
<div class="wrapper">
<div class="content">
<h1 class="loginH1">Caloris: [cal:def(basic;title) /]</h1>' . PHP_EOL;

$content .= $formLogin;

if ($_GET["action"] == 'passLost') {
    $textPass = '
<div style="margin: 0 auto;">
<p class="perex">' . t('lostPasswordInfoEmail', 'administrator') . '</p>
<form action="' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php" method="post" class="loginForm cform" style="width: 450px;">
<input type="hidden" name="action" value="passLostRetrieve" />
<p>' . t('yourEmailAddress', 'administrator') . ': <input type="text" name="email" /> <input type="submit" value="Odeslat" /></p>
</form>
</div>
' . PHP_EOL;
} else {
    $textPass = '<p style="text-align: center; margin: 10px 0 0 0;"><a href="[cal:def(paths;uri) /][cal:def(dirs;admin) /]/login.php?action=passLost">[cal:t(forgetPassword;administrator) /]</a><p>' . PHP_EOL;
}

if ($_GET["action"] == 'passRetrieve') {
    $textPass = '
<h1>Nové heslo</h1>

<form action="' . _CALSET_PATHS_URI . _CALSET_DIRS_ADMIN . '/login.php" method="post" class="loginForm cform">
<input type="hidden" name="action" value="passRetrieveReset"  />
<input type="hidden" name="email" value="' . $_GET["email"] . '"  />
<input type="hidden" name="activation" value="' . $_GET["code"] . '"  />
<table>
    <tr>
        <td>Nové heslo:</td>
        <td><input type="password" name="pwd" /></td>
    </tr>
    <tr>
        <td>Zadejte heslo znovu:</td>
        <td><input type="password" name="pwd2" /></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" value="Nastavit" /></td>
    </tr>
</table>
</form>';
}

$content .= '
<p style="color: red; text-align: center; margin: 10px 0;">' . $_REQUEST["msg"] . '</p>

' . $textPass . '
</div>
</div>
</body>
</html>';

echo Caloris\Template::parse($content);